<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="danger" @click="exportExcel">简单表头导出</el-button>
          <el-button size="small" type="info">复杂表头导出</el-button>
          <el-button size="small" type="success" @click="$router.push('/employees/import')">Excel导入</el-button>
          <el-button size="small" type="primary" @click="isShowDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- table -->
      <el-card>
        <el-table border :data="list">
          <el-table-column align="center" prop="index" label="序号" sortable="" />
          <el-table-column align="center" prop="username" label="姓名" sortable="" />
          <el-table-column align="center" prop="staffPhoto" label="头像" sortable="">
            <template v-slot="{row}">
              <img v-fixPhoto :src="row.staffPhoto" alt="" style="width:100px">
            </template>
          </el-table-column>
          <el-table-column align="center" prop="mobile" label="手机号" sortable="" />
          <el-table-column align="center" prop="workNumber" label="工号" sortable="" />
          <el-table-column align="center" prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatEemployees" />
          <el-table-column align="center" prop="departmentName" label="部门" sortable="" />
          <!-- <el-table-column align="center" prop="timeOfEntry" label="入职时间" sortable="" :formatter="formatTime" /> -->
          <el-table-column align="center" label="入职时间" sortable="">
            <template v-slot="{row}">
              <!-- {{ row.timeOfEntry | formatTime }} -->
              <!-- {{dayjs(row.timeOfEntry).format('YYYY/MM/DD') }} -->
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="账户状态" sortable="">
            <template v-slot="{row}">
              <!-- v-model=:value+@input -->
              <el-switch
                :value="row.enableState"
                :active-value="1"
                :inactive-value="'1'"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="ShowRoleDialog(row.id) ">角色</el-button>
              <el-button type="text" size="small" :disabled="row.enableState==='1'" @click="delUser(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageConfig.size" @current-change="currentChange" @prev-click="prevClick" @next-click="nextClick" />
        </el-row>
      </el-card>
      <add-employee :is-show-dialog="isShowDialog" @handleClose="handleClose" @render="render" />
      <assign-role ref="assignRole" :is-show-role-dialog="isShowRoleDialog" @closeDialog="isShowRoleDialog=false" />
    </div>
  </div>
</template>

<script>
import { getAllUser, delEmployee } from '@/api/employees'
import { getUserDatailById } from '@/api/permisson'
import employees from '@/constant/employees'
// import dayjs from 'dayjs'
// 引入导出函数
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployee from '@/components/add-employee'
import AssignRole from './assignRole.vue'

export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  // filters: {
  //   formatTime(oldvalue) {
  //     if (oldvalue) {
  //       return dayjs(oldvalue).format('YYYY/MM/DD')
  //     } else {
  //       return '1970/1/1'
  //     }
  //   }
  // },
  data() {
    return {
      isShowDialog: false,
      isShowRoleDialog: false,
      list: [],
      pageConfig: {
        page: 1,
        size: 4
      },
      total: 0
    }
  },
  async created() {
    await this.render()
  },
  methods: {
    // 渲染函数
    async render() {
      const { data } = await getAllUser(this.pageConfig)
      this.total = data.total

      this.list = data.rows.map((item, index) => {
        return { ...item,
          index: (this.pageConfig.page - 1) * this.pageConfig.size + index + 1,
          departmentName: item.departmentName ? item.departmentName : '厕所' }
      })
    },
    // 点击页码跳转
    async  currentChange(current) {
      this.pageConfig.page = current
      await this.render()
    },
    // 上一页
    async prevClick() {
      this.pageConfig.page--
      await this.render()
    },
    // 下一页
    async nextClick() {
      this.pageConfig.page++
      await this.render()
    },
    formatEemployees(row, col, val) {
      // const hiretype = [
      //   { id: 1, value: '正式' },
      //   { id: 2, value: '劳务派遣' },
      //   { id: 3, value: '实习生' },
      //   { id: 4, value: '临时工' }
      // ]
      const res = employees.hireType.find(v => v.id === val)
      return res ? res.value : '未知'
    },
    // 删除
    async delUser(id) {
      try {
        await this.$confirm('你确认要删除吗？')
        await delEmployee(id)
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.total !== 1) {
          this.pageConfig.page--
        }
        return this.render()
      } catch (error) {
        this.$message.warning('取消删除')
      }
    },
    // 开启角色权限弹框
    async ShowRoleDialog(id) {
      console.log(id)
      this.isShowRoleDialog = true
      const { data } = await getUserDatailById(id)
      this.$refs.assignRole.checkList = data.roleIds
      this.$refs.assignRole.id = id
    },
    // 关闭弹窗
    handleClose() {
      this.isShowDialog = false
    },
    //     // 重置
    //     reset(){
    // this
    //     } ,
    // 文件导出 中
    async exportExcel() {
      // 1. 获取所有员工数据
      const { data } = await getAllUser({
        page: 1,
        size: this.total
      })
      const { rows } = data
      // 数组映射
      const type = {
        '用户名': 'username',
        '手机号': 'mobile',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry' }
      // 2. 转成 excel 文件供用户下载
      export_json_to_excel({
        // 遍历key名字
        header: Object.keys(type),
        data: rows.map(item => {
          const arr = []
          // 开始循环
          for (const key in type) {
            // 入职方式处理
            if (type[key] === 'formOfEmployment') {
              const res = employees.hireType.find(it => it.id === item[type[key]])
              arr.push(res ? res.value : '未知')
              // 入职时间处理
            } else if (type[key] === 'timeOfEntry') {
              arr.push(formatDate(item[type[key]]))
            } else {
              arr.push(item[type[key]])
            }
          }
          return arr
        })
      })
    }
  }
}
</script>

<style>

</style>
